package com.hup.winHolderService.framework.exception;

import com.hup.winHolderService.framework.model.ExceptionResult.BaseResultException;
import com.hup.winHolderService.framework.util.net.HttpUtil;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;

import javax.servlet.http.HttpServletRequest;

/**
 * msg=无权访问
 * 401或403返回码
 *
 * @author hugan
 * @date 2023/7/12
 */
@Slf4j
public class AppAccessException extends RuntimeException implements BaseResultException {

    @Getter
    private HttpStatus status;
    private boolean showLog;

    public AppAccessException(String message) {
        super(message);
    }

    @Override
    public String getRespMessage() {
        return "无权访问";
    }

    public AppAccessException setShowLog(boolean showLog) {
        this.showLog = showLog;
        return this;
    }

    public static AppAccessException e401(String msg) {
        AppAccessException e = new AppAccessException(msg);
        e.status = HttpStatus.UNAUTHORIZED;
        return e;
    }

    public static AppAccessException e403(String msg) {
        AppAccessException e = new AppAccessException(msg);
        e.status = HttpStatus.FORBIDDEN;
        return e;
    }

    @Override
    public void doLog() {
        if (showLog) {
            HttpServletRequest request = HttpUtil.getRequest();
            String userAgent = request.getHeader("User-Agent");
            String ipAddr = HttpUtil.getIpAddr(request);
            log.error("uri={}, msg={}, ip={}, agent={}",
                    request.getRequestURI(), getMessage(),
                    ipAddr, userAgent);
        }
    }
}
